package com.yzk.train.${module}.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yzk.train.common.response.PageResp;
import com.yzk.train.common.utils.SnowUtil;
import com.yzk.train.${module}.entity.${Domain};
import com.yzk.train.${module}.entity.${Domain}Example;
import com.yzk.train.${module}.mapper.${Domain}Mapper;
import com.yzk.train.${module}.request.${Domain}QueryReq;
import com.yzk.train.${module}.request.${Domain}SaveReq;
import com.yzk.train.${module}.response.${Domain}QueryResp;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ${Domain}Service {

    @Resource
    private ${Domain}Mapper ${domain}Mapper;

    /**
* 保存 / 更新 ${tableNameCn}
     * @param req
     */
    public String save(${Domain}SaveReq req) {
        ${Domain} ${domain} = BeanUtil.copyProperties(req, ${Domain}.class);
        DateTime now = DateTime.now();
        ${domain}.setUpdateTime(now);
        if (ObjectUtil.isNull(${domain}.getId())) {
            ${domain}.setId(SnowUtil.getSnowflakeNextId());
            ${domain}.setCreateTime(now);
            ${domain}Mapper.insert(${domain});
            return "保存成功";
        } else {
            ${domain}Mapper.updateByPrimaryKeySelective(${domain});
            return "编辑成功";
        }
    }

    /**
     * 查询${tableNameCn}列表
     * @param req
     */
    public PageResp<${Domain}QueryResp> queryList(${Domain}QueryReq req) {
        ${Domain}Example ${domain}Example = new ${Domain}Example();
        ${domain}Example.setOrderByClause("id desc");
        // 使用分页插件
        PageHelper.startPage(req.getPageNum(), req.getPageSize());
        List<${Domain}> ${domain}s = ${domain}Mapper.selectByExample(${domain}Example);
        // 使用 PageInfo 包装查询结果
        PageInfo<${Domain}> pageInfo = new PageInfo<>(${domain}s);
        // 转换为 PageResp
        List<${Domain}QueryResp> list = BeanUtil.copyToList(${domain}s, ${Domain}QueryResp.class);
        return new PageResp<>(pageInfo.getTotal(), list);
    }

    /**
     * 根据ID删除${tableNameCn}
     * @param id
     */
    public void delete(Long id) {
        ${domain}Mapper.deleteByPrimaryKey(id);
    }

}
